#!/usr/bin/perl

package Log;

use strict;
use warnings;
use Exporter 'import';

use Utils qw(dd date);
use Consts;

my $level_primary = 0b00000001;
my $level_debug   = 0b00000010;
my $level_info    = 0b00000100;
my $level_warn    = 0b00001000;
my $level_error   = 0b00010000;
my $level_fatal   = 0b00100000;

my $level = $level_primary | $level_debug | $level_info | $level_warn | $level_error | $level_fatal;

sub setLevel
{
    my $l = shift;
    $level = $l;
}

sub getLevel
{
    return $level;
}

sub _print
{
    my $level = shift;
    my $msg   = shift;
    my $time  = date();

    my $color = '';
    if ($level eq 'PRIMARY') {
        $color = "\033[34m";
    } elsif ($level eq 'DEBUG') {
        $color = "\033[37m";
    } elsif ($level eq 'INFO') {
        $color = "\033[0m";
    } elsif ($level eq 'WARN') {
        $color = "\033[33m";
    } elsif ($level eq 'ERROR') {
        $color = "\033[31m";
    } elsif ($level eq 'FATAL') {
        $color = "\033[35m";
    } elsif ($level eq 'SUCCESS') {
        $color = "\033[32m";
    } else {
        $color = "\033[0m";
    }
    print "[${time}] [$$] [${level}] ${color}${msg}\033[0m\n";

    # 使用全限定变量名替换导入变量
    my $logfile_path = $Consts::LOG_PATH . $Consts::DS . date(time(), '%Y%m%d') . '.log';
    open(my $fh, '>>', $logfile_path) or die "Cannot open file: $logfile_path";
    print $fh "[${time}] [$$] [${level}] ${msg}\n";
    close($fh);
}
sub primary
{
    my $msg = shift;
    _print('PRIMARY', $msg);
}

sub debug
{
    my $msg = shift;
    _print('DEBUG', $msg);
}

sub info
{
    my $msg = shift;
    _print('INFO', $msg);
}

sub warn
{
    my $msg = shift;
    _print('WARN', $msg);
}

sub error
{
    my $msg = shift;
    _print('ERROR', $msg);
}

sub fatal
{
    my $msg = shift;
    _print('FATAL', $msg);
}

sub success
{
    my $msg = shift;
    _print('SUCCESS', $msg);
}

1;
